package com.willpower.eureka.controller;

import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import com.willpower.eureka.auth.response.Result;
import com.willpower.eureka.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: wen-yi;
 * @date: 2021/11/5 19:12;
 * @Description:
 */
@RestController
public class CaptchaController {
    @Autowired
    private RedisUtil redisUtil;

    @ResponseBody
    @RequestMapping("/captcha")
    public Result captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //宽、高、位数 SpecCaptcha | GifCaptcha | ChineseCaptcha | ChineseGifCaptcha | ArithmeticCaptcha
        GifCaptcha captcha = new GifCaptcha(130, 48, 5);
        // 设置字体  有默认字体，可以不用设置
        // specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32)); 原字体好看些
        // 1 - 10
        // chineseCaptcha.setFont(Captcha.FONT_1);
        // 只有SpecCaptcha和GifCaptcha设置才有效果：设置类型，纯数字、纯字母、字母数字混合
        // TYPE_DEFAULT|TYPE_ONLY_NUMBER|TYPE_ONLY_CHAR|TYPE_ONLY_UPPER|TYPE_ONLY_LOWER|TYPE_NUM_AND_UPPER
        // gifCaptcha.setCharType(Captcha.TYPE_DEFAULT);
         String verCode = captcha.text().toLowerCase();
        // String key = UUID.randomUUID().toString();
        // 存入redis并设置过期时间为30分钟
        redisUtil.setEx("aj", verCode, 1, TimeUnit.MINUTES);
        // 将key和base64返回给前端
        Map<String,Object> data = new HashMap<>();
        data.put("key", "aj");
        data.put("image", captcha.toBase64());
        return Result.ok(data);
    }
}
